package com.example.lin.utils;

import com.example.lin.entity.pojo.Permission;
import com.example.lin.entity.vo.MetaVo;
import com.example.lin.entity.vo.RouterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Administrator
 */
@Component
public class TreeUtil {

    private TreeUtil() {}

    /**
     * 构建路由树
     * @param nodes 结点数组
     * @param id 父节点id
     * @return list
     */
    public static List<RouterVo> routerTree(List<Permission> nodes, Integer id) {
        List<RouterVo> routers = new ArrayList<>();
        Optional.ofNullable(nodes).orElse(new ArrayList<>())
                .stream()
                .filter(item -> ObjectUtils.isEmpty(item) && item.getParentId().equals(id))
                .forEach(item -> {
                    RouterVo router = new RouterVo();
                    if (item.getParentId().equals(0)) {
                        router.setComponent("Layout");
                        router.setAlwaysShow(true);
                    } else {
                        router.setName(item.getLabel()).setHidden(false).setPath(item.getPath()).setComponent(item.getComponent()).setAlwaysShow(false);
                    }
                    router.setMeta(new MetaVo(item.getRoles(), item.getLabel(), item.getIcon(), false, false, false, ""));
                    List<RouterVo> children = routerTree(nodes, item.getId());
                    router.setChildren(children);
                    routers.add(router);
                });
        return routers;
    }

    /**
     * 构建权限树
     * @param nodes 结点数组
     * @param id 父节点id
     * @return list
     */
    public static List<Permission> permissionTree(List<Permission> nodes, Integer id) {
        List<Permission> permissions = new ArrayList<>();
        Optional.ofNullable(nodes).orElse(new ArrayList<>())
                .stream()
                .filter(item -> ObjectUtils.isEmpty(item) && item.getParentId().equals(id))
                .forEach(item -> {
                    Permission permission = new Permission();
                    BeanUtils.copyProperties(item, permission);
                    permissions.add(permission);
                    List<Permission> children = permissionTree(nodes, item.getId());
                    permission.setChildren(children);
                    permissions.addAll(children);
                });
        return permissions;
    }
}
